#include <iostream>
#include <fstream>
#include "TROOT.h"
#include "TString.h"
#include "TFile.h"
#include "TTree.h"
#include "TGraph.h"
#include "TSpectrum.h"
#include "TMath.h"
#include "TSystem.h"
#include "TPostScript.h"
#include "TTimeStamp.h"
#include "TSpectrum.h"
#include "iostream"

#include "trackHandle.h"

#include <vector>
#include <string>
#include <algorithm>
#include <regex>
#include <sys/stat.h>

#include <opencv2/opencv.hpp>
#include <opencv2/ximgproc.hpp>

using namespace std;
using namespace cv;
const int NX = 72;
const int NY = 72;

std::vector<std::string> SplitStr(const char* Str, const char* Split)
{
    std::string VStr(Str);
    std::vector<std::string> Vector;
    std::regex Delimiter(Split);
    std::sregex_token_iterator iter(VStr.begin(), VStr.end(), Delimiter, -1);
    std::sregex_token_iterator end;
    while (iter != end)
    {   
        Vector.push_back(std::string(*iter));
        ++iter;
    }
    return Vector;
}

int main(int argc, char **argv)
{
    TString inputFile = "";
    TString outputName = "";
    TString simFile = "";
    TString treeName = "t_data";
    if (argc >= 2)
    {
        for(int iA = 1; iA < argc; ++iA)
        {
            if(TString(argv[iA][0]) == TString("-"))
            {
                if(TString(argv[iA]) == TString("-t"))
                {
                    treeName = TString(argv[iA + 1]);
                    ++iA;
                }
                if(TString(argv[iA]) == TString("-o"))
                {
                    outputName = TString(argv[iA + 1]);
                    ++iA;
                }
                if(TString(argv[iA]) == TString("-s"))
                {
                    simFile = TString(argv[iA + 1]);
                    ++iA;
                }
            }
            else if(SplitStr(argv[iA], "\\.").back() == std::string("root"))
            {
                inputFile = TString(argv[iA]);
            }
        }
    }
    if(inputFile == TString(""))
    {
        std::cerr << "Digitize file name must be provide." << std::endl;
    }
    if(outputName == TString(""))
    {
        outputName = inputFile[0];
        outputName.ReplaceAll(".root", "_MCfeature.root");
    }

    TrackHandle TH(10);
    std::vector<myTrack> Vtrack;  
    TFile *outFile = new TFile(outputName,"recreate"); 
    //TTree *outTree = new TTree(treeName,"data feature result");
    TTree* outTree = TH.calculate(inputFile, treeName, simFile);

    outFile->cd();
    outTree->AutoSave();
    outFile->Close();

    std::cout << "File Fearture Extraction Completed" << std::endl;
	return 0;

}
